<template>
<div class="mapContainer">
  <div class="searchPanel">
    <el-row :gutter="24">
      <el-col :span="20">
        <el-select v-model="currentCode" placeholder="请选择" @change="areaChange" size="medium">
          <el-option v-for="item in areaOptions" :key="item.code" :label="item.name" :value="item.code">
          </el-option>
        </el-select>
        <!-- <el-cascader v-model="areaCode" :options="areaOptions" clearable :props="areaProps" placeholder="请选择" filterable class="cas" @change="areaChange"></el-cascader> -->
        <el-button :type="(currentIndex == -1) ? 'primary' : ''" @click="getCurrentGround({},-1)" class="ml10" size="medium">全部</el-button>
        <el-button size="medium" v-for="(item,index) in paramsAtrr.groundTypeOptions" :key="index" :type="index == currentIndex ? 'primary' : ''" @click="getCurrentGround(item,index)">{{item.name}}</el-button>
      </el-col>
      <el-col :span="4">
        当前可视区域共有 {{getNum()}} 个场点
      </el-col>
    </el-row>

  </div>

  <baidu-map class="map" :center="center" :zoom="paramsAtrr.zoom" :min-zoom="minzoom" :scroll-wheel-zoom="scrollwheelzoom" :mapClick="false" @ready="handleReady" @zoomend="handleZoomChange" @dragend="handleGragend">

    <!-- 比例尺 -->
    <bm-scale anchor="BMAP_ANCHOR_TOP_RIGHT"></bm-scale>

    <!-- 缩放控件 -->
    <bm-navigation anchor="BMAP_ANCHOR_BOTTOM_RIGHT"></bm-navigation>

    <!-- 地图类型 -->
    <!-- <bm-map-type :map-types="['BMAP_NORMAL_MAP', 'BMAP_HYBRID_MAP']" anchor="BMAP_ANCHOR_TOP_LEFT"></bm-map-type> -->

    <!-- 缩放比例小于等于ZOOMBOUNDARY时显示统计数 -->
    <div v-if="paramsAtrr.zoom <= paramsAtrr.ZOOMBOUNDARY">
      <template v-for="(item, index) in allStatistics">
        <zone-overlay :key="index" :position="{ lng: item.center[0], lat: item.center[1] }" :text="item" @mouseover.native="selectZone(item, index)" @mouseleave.native="cancelZone()" @click.native="selZone(item, index)" :paramsAtrr="paramsAtrr">
        </zone-overlay>
      </template>
    </div>

    <!-- 缩放比例大于ZOOMBOUNDARY时显示具体点位 -->
    <div v-if="paramsAtrr.zoom > paramsAtrr.ZOOMBOUNDARY">

      <template v-for="(item, index) in zoneGeoPoints">
        <zone-overlay :key="index" :position="{ lng: item.coordinate.split(',')[0], lat: item.coordinate.split(',')[1] }" :text="item" @mouseover.native="selectZone(item, index)" @mouseleave.native="cancelZone()" @click.native="showInfo(item,index)"
          :paramsAtrr="paramsAtrr">
        </zone-overlay>
        <!-- <bm-marker :key="index" :position="{ lng: item.coordinate.split(',')[0], lat: item.coordinate.split(',')[1] }" @click="showInfo(item)"
        :icon="{url: getImgUrl(item), size: { width: 40, height: 40 }}">
         <bm-label :content="item.coordinate" :labelStyle="{color: 'red', fontSize : '24px'}"></bm-label>
        </bm-marker> -->
      </template>
    </div>

    <!-- <div v-if="!showZone">
      <around-overlay v-for="(item, index) in aroundGeoPoints" :key="index" :position="{ lng: item.lng, lat: item.lat }" :text="item"></around-overlay>
    </div> -->

    <!-- 区域边界 -->
    <bm-boundary v-if="showBoundary" :name="zoneBoundary" :strokeWeight="2" strokeColor="blue" fillColor="skyblue" :fillOpacity="0.4"></bm-boundary>

    <div v-if="labelShow" v-for="(item, index) in markers" :key="index">
      <labelOVerlay v-for="(item, index) in markers" :key="index" :position="{ lng: item.lng, lat: item.lat }" :text="item.community" @click.native="drawerClick(item, index)"></labelOVerlay>
    </div>

    <!-- 显示具体点位时单击点位显示详情 -->
    <bm-info-window :position="infoAttr.infoCardPosition" :show="infoAttr.isShowInfo" :width="400" :autoPan="false" @close="infoWindowClose" @open="infoWindowOpen">
      <GroundInfo :infoData="infoAttr.infoData" style="padding:10px 30px"></GroundInfo>
      <p>{{infoAttr.infoCardPosition}}</p>
    </bm-info-window>

    <!-- 定位当前地址： -->
    <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" :showAddressBar="true" :autoLocation="true"></bm-geolocation>
  </baidu-map>
</div>
</template>
<script>
import {
  areadata
} from '../../mock/mockdata.js'
import {
  treeDataTranslate
} from '@/utils';
import zoneOverlay from './zoneOverlay.vue';
import labelOVerlay from './labelOVerlay.vue';
import aroundOverlay from './aroundOverlay.vue';
import detailOverlay from './detailOverlay.vue';
import GroundInfo from './groundInfo.vue'
import DetailList from './detailList.vue'
import type1Img from '@/assets/type1.png'
import type1ActiveImg from '@/assets/type1Active.png'
import type2Img from '@/assets/type2.png'
import type2ActiveImg from '@/assets/type2Active.png'
import type3Img from '@/assets/type3.png'
import type3ActiveImg from '@/assets/type3Active.png'
import type4Img from '@/assets/type4.png'
import type4ActiveImg from '@/assets/type4Active.png'
import type1Url from '@/assets/type11.png'
import type2Url from '@/assets/type12.png'
import type3Url from '@/assets/type13.png'
import type4Url from '@/assets/type14.png'
const Debounce = function(fn, callback, timeout = 1000 * 1) {
  if (fn.disable === true) {
    return console.log('防抖作用于：' + fn.name);
  } else {
    fn.disable = true;
    const timeoutPromise = new Promise(res => {
      setTimeout(res, timeout);
    });
    Promise.all([fn(), timeoutPromise]).finally(() => {
      fn.disable = false;
      callback && callback();
    });
  }
};
export default {
  components: {
    zoneOverlay,
    labelOVerlay,
    aroundOverlay,
    detailOverlay,
    DetailList,
    GroundInfo
  },
  data() {
    return {
      title: '',
      direction: 'rtl',
      drawer: false,
      innerDrawer: false,
      active: false,
      center: {
        lng: 116.41338,
        lat: 39.91092
      },
      minzoom: 10,
      scrollwheelzoom: true,
      zoneGeoPoints: null,
      aroundGeoPoints: null,
      showZone: true,
      zoneBoundary: null,
      showBoundary: false,
      markers: null,
      show: true,
      labelShow: false,
      toggleDetail: false,
      formData: {},
      infoPromise: null,
      detailGeo: null,
      vertexPoint: null,
      detailAddress: null,
      currentCode: null,
      areaOptions: [],
      areaProps: {
        value: 'code',
        label: 'name'
      },
      currentIndex: -1,
      detailData: [],
      allStatistics: [], //全部类型全部区域统计数
      paramsAtrr: {
        zoom: 10,
        ZOOMBOUNDARY: 14,
        groundTypeOptions: [],
        currentType: "-1",
      },
      infoAttr: {
        infoCardPosition: {},
        isShowInfo: false,
        infoData: {}
      }
    };
  },
  created() {
    this.initData();
    this.getStatisticsData()
  },
  mounted() {},
  methods: {
    initData() {
      this.$api.getDicOptions({
        params: {
          dictCode: "GroundType"
        }
      }).then((res) => {
        this.paramsAtrr.groundTypeOptions = res;
        this.paramsAtrr.typeOptions = res;
      }).catch((err) => {
        this.$message.error(err)
      })
      this.$api.getAllArea({
        levels: ['province', 'city', 'district']
      }).then((res) => {
        res.splice(res.findIndex(item => item.level === 'city'), 1)
        this.areaOptions = res;
        this.currentCode = this.areaOptions.find(x => x.name == "北京市").code
      }).catch((err) => {
        this.$message.error(err)
      })
    },
    handleReady({
      BMap,
      map
    }) {
      this.center = map.getCenter();
      this.vertexPoint = map.getBounds().getSouthWest();
    },
    handleSetPoint(e) {
      // 获取移动后地图中心点
      this.center = e.target.getCenter();
      // 获取移动后地图左上角点
      this.vertexPoint = e.target.getBounds().getSouthWest();
    },
    handleGetNearPoint() {
      let params = {};
      if (this.paramsAtrr.currentType == '-1') {
        params = {
          center: this.center,
          scale: this.paramsAtrr.zoom,
          vertex: this.vertexPoint
        }
      } else {
        params = {
          center: this.center,
          groundType: this.paramsAtrr.currentType,
          scale: this.paramsAtrr.zoom,
          vertex: this.vertexPoint
        }
      }
      this.$api.getNearByGround(params).then(res => {
        this.zoneGeoPoints = res;
      })

    },
    handleGragend(e) {
      this.handleSetPoint(e);
      if (this.paramsAtrr.zoom > this.paramsAtrr.ZOOMBOUNDARY) { //缩放比例大于ZOOMBOUNDARY时获取具体点位
        this.handleGetNearPoint();
      }
    },
    handleZoomChange(e) {
      this.paramsAtrr.zoom = e.target.getZoom();
      this.handleSetPoint(e);
      if (this.paramsAtrr.zoom > this.paramsAtrr.ZOOMBOUNDARY) {
        this.handleGetNearPoint();
      } else {
        this.showZone = true;
      }
    },
    selectZone(item, index) {
      this.zoneBoundary = item.posCity + item.name + '';
      this.showCurInfo(item);
    },
    cancelZone() {
      this.zoneBoundary = '';
      this.hideCurInfo();
    },
    selZone(item, index) {
      this.showZone = false;
      this.zoneBoundary = '';
      this.showBoundary = false;
      this.center.lng = item.center[0];
      this.center.lat = item.center[1];
      this.paramsAtrr.zoom = this.paramsAtrr.ZOOMBOUNDARY + 1
      this.$set(this, "currentCode", item.districtCode)

      // this.handleGetNearPoint();
    },
    showCurInfo(item, index) {
      this.infoPromise = new Promise(resolve => {
        Debounce(() => {
          this.detailGeo = item;
          this.toggleDetail = true;
          resolve();
        });
      });
      return this.infoPromise;
    },
    hideCurInfo() {
      // this.toggleDetail = false;
    },
    draw({
      el,
      BMap,
      map
    }) {
      const pixel = map.pointToOverlayPixel(new BMap.Point(el.lng, el.lat));
      el.style.left = pixel.x - 60 + 'px';
      el.style.top = pixel.y - 20 + 'px';
    },
    setImgUrl(item, index) {
      let me = this;
      if (item.id == "1") {
        return (index == me.currentIndex) ? type1ActiveImg : type1Img
      } else if (item.id == "2") {
        return (index == me.currentIndex) ? type2ActiveImg : type2Img
      } else if (item.id == "3") {
        return (index == me.currentIndex) ? type3ActiveImg : type3Img
      } else {
        return (index == me.currentIndex) ? type4ActiveImg : type4Img
      }
      return type1Img
    },
    getCurrentGround(item, index) {
      let me = this;
      me.paramsAtrr.currentType = item.id || '-1';
      me.currentIndex = index;
      if (me.currentCode != me.areaOptions.find(x => x.name == "北京市").code) {
        let obj = me.allStatistics.filter(x => x.districtCode == me.currentCode)[0];
        me.center.lng = obj.center[0];
        me.center.lat = obj.center[1];
        if (me.paramsAtrr.zoom <= me.paramsAtrr.ZOOMBOUNDARY) {
          me.paramsAtrr.zoom = me.paramsAtrr.ZOOMBOUNDARY + 1
        }
        me.handleGetNearPoint()
      } else {
        me.paramsAtrr.zoom = 10;
        me.getStatisticsData();
      }

    },
    getStatisticsData() {
      let me = this;
      me.$api.getStatistics().then((res) => {
        me.allStatistics = res;
      })
    },
    areaChange(val) {
      let me = this;
      if (val == me.areaOptions.find(x => x.name == "北京市").code) {
        me.paramsAtrr.zoom = 10;
        me.center = {
          lng: 116.413387,
          lat: 39.910924
        };
      } else {
        me.allStatistics.forEach((item, i) => {
          if (item.districtCode == val) {
            me.selZone(item, i)
          }
        });
      }
    },
    getNum() {
      if (this.paramsAtrr.zoom > this.paramsAtrr.ZOOMBOUNDARY) {
        if (this.zoneGeoPoints) {
          return this.zoneGeoPoints.length
        } else {
          return 0
        }
      } else {
        if (this.allStatistics) {
          return this.allStatistics.length
        } else {
          return 0
        }
      }
    },
    //单击具体点位显示详情窗体
    showInfo(item, index) {
      this.infoAttr.infoCardPosition = {
        lng: item.coordinate.split(',')[0],
        lat: item.coordinate.split(',')[1]
      };
      this.infoAttr.infoData = item;
      // this.$nextTick(() => {
        this.infoAttr.isShowInfo = true
      // })
      console.log("item.coordinate:",item.coordinate)
      console.log('this.infoAttr.infoCardPosition:',this.infoAttr.infoCardPosition)

    },
    infoWindowClose() {
      this.infoAttr.isShowInfo = false
    },
    infoWindowOpen() {
      this.infoAttr.isShowInfo = true
    },
    getImgUrl(item){
      if(item.groundType == "1"){
        return type1Url
      }else if (item.groundType == "2"){
        return type2Url
      }else if (item.groundType == "2"){
        return type3Url
      }else{
        return type4Url
      }
    }
  }
};
</script>

<style lang="less">
.mapContainer {
    width: 100%;
    height: 100vh;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    font-size: 14px;
    .searchPanel {
        width: 100%;
        height: 50px;
        line-height: 50px;
        border-bottom: 1px solid #f3f3f3;
        padding: 10px 20px;
    }
    .map {
        width: 100%;
        // min-height: 600px;
        flex: 1;
    }
}

.BMapLabel {
    border-radius: 8px;
    font-family: 'Courier New', Courier, monospace;
    letter-spacing: 0;
    line-height: 12px;
}

.sample {
    width: 120px;
    height: 40px;
    line-height: 40px;
    background: rgba(0, 0, 0, 0.5);
    overflow: hidden;
    box-shadow: 0 0 5px #000;
    color: #fff;
    text-align: center;
    padding: 10px;
    position: absolute;
}

.sample.active {
    background: rgba(0, 0, 0, 0.75);
    color: #fff;
}

.BMap_cpyCtrl {
    display: none;
}

.anchorBL {
    display: none;
}
.input-with-select {
    .el-input-group__prepend {
        background-color: #fff;
        padding: 0;
        border: none;
    }
}
.cover {
    margin-top: 20px;
    margin-left: 20px;
    width: 100%;
}
.cas {
    width: 300px;
}
.active {
    color: #1296db;
    font-weight: bolder;
}
.typeItem {
    display: inline-block;
    width: 120px;
    padding: 0 15px;
    font-size: 15px;
    .label {
        vertical-align: middle;
    }
}
.typeItem:hover {
    color: #F5A1A2;
    cursor: pointer;
}
.imgStyle {
    display: inline-block;
    width: 30px;
    height: 30px;
    vertical-align: middle;
}
</style>
